<template>
  <div class="messages-container">
    <div class="friend-item world-channel" @click="goToGroupChat">
      <el-avatar :src="defaultAvatar" size="large" />
      <div class="friend-info">
        <span class="username">世界频道</span>
        <div class="message-bubble">
          <p class="last-message">{{ latestGroupMessages[0]?.message || '暂无消息' }}</p>
          <span class="last-message-time">{{ latestGroupMessages[0]?.timestamp ? formatTimestamp(latestGroupMessages[0].timestamp) : '' }}</span>
        </div>
      </div>
    </div>
    <div v-for="friend in recentFriends" :key="friend.id" class="friend-item" @click="startChat(friend)">
      <el-avatar :src="friend.avatar || defaultAvatar" size="large" />
      <div class="friend-info">
        <span class="username">{{ friend.username }}</span>
        <div class="message-bubble">
          <p class="last-message">{{ friend.lastMessage }}</p>
          <span class="last-message-time">{{ friend.lastMessageTime ? formatTimestamp(friend.lastMessageTime) : '' }}</span>
        </div>
        <div v-if="friend.unreadCount && friend.unreadCount > 0" class="notification-badge">
          {{ friend.unreadCount }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { defaultAvatar } from '@/assets/defaultAvatar';

interface Friend {
  id: string;
  username: string;
  avatar?: string;
  lastMessage?: string;
  lastMessageTime?: string;
  unreadCount?: number;
  unreadMessageIds: string[];
}

interface GroupMessage {
  id: number;
  sender_id: number;
  message: string;
  timestamp: string;
}

const router = useRouter();
const recentFriends = ref<Friend[]>([]);
const latestGroupMessages = ref<GroupMessage[]>([]);

const formatTimestamp = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString();
};

const getRecentFriends = async () => {
  try {
    const userId = localStorage.getItem('userId');
    const response = await axios.get(`${API_BASE_URL}/${userId}/recentFriends`);
    recentFriends.value = response.data;
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '获取最近聊天好友失败');
  }
};

const getLatestGroupMessages = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/all-group/recent-messages?limit=5`);
    latestGroupMessages.value = response.data;
  } catch (error: any) {
    console.error('获取最新群聊消息失败:', error);
  }
};

const markMessagesAsRead = async (messageIds: string[]) => {
  try {
    await axios.post(`${API_BASE_URL}/messages/read`, {
      messageIds: messageIds
    });
  } catch (error: any) {
    console.error('标记消息为已读失败:', error);
  }
};

const startChat = async (friend: Friend) => {
  try {
    // 获取聊天记录
    const response = await axios.get(`${API_BASE_URL}/chat/${localStorage.getItem('userId')}/${friend.id}`);
    const messages = response.data;

    // 筛选未读消息的 ID
    const unreadMessageIds = messages
      .filter((message: any) => message.isRead === 0)
      .map((message: any) => message.id);

    // 如果有未读消息，标记为已读
    if (unreadMessageIds.length > 0) {
      markMessagesAsRead(unreadMessageIds);
    }
  } catch (error: any) {
    console.error('获取聊天记录失败:', error);
  }

  router.push(`/chat/${friend.id}`);
};

const goToGroupChat = () => {
  router.push('/group-chat');
};

onMounted(() => {
  getRecentFriends();
  getLatestGroupMessages();
});
</script>

<style scoped>
.messages-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.world-channel {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.friend-item {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.friend-item:hover {
  background-color: #f5f7fa;
}

.friend-info {
  flex: 1;
  position: relative;
}

.username {
  font-size: 1.1em;
  font-weight: bold;
}

.message-bubble {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 10px;
  margin-top: 5px;
}

.last-message {
  color: #999;
  font-size: 0.9em;
  margin: 0;
}

.last-message-time {
  color: #ccc;
  font-size: 0.8em;
  margin: 0;
}

.notification-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8em;
}
</style> 